package dbtools;

/**
 * Title:  取得数据库连接参数
 * Desc :  使用 runConfig.xml  文件
 */

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Hashtable;

public class DBInitVO {
	private static DBInitVO uniqueInstance = null;
	private Hashtable hashKey;
	private String nowpath;

	/**
	 * 构造子
	 */
	private DBInitVO() {
	}

	public void setNowPath(String realpath) {
		nowpath = realpath;
	}

	public String getNowPath() {
		return nowpath;
	}

	private void makeDbConn(String dbname, String valueName) {
		try {
			SAXReader reader = new SAXReader();
			InputStream input = new FileInputStream(new File("Config//runConfig.xml"));
			Document document = reader.read(input);
			Element root = document.getRootElement();
			Object obj_root[] = root.elements().toArray();
			int iLen = obj_root.length;
			int i = 0;
			do {
				if (i >= iLen)
					break;
				Element child = (Element) obj_root[i];
				if (child.attribute("name").getValue().equals(dbname)) {
					Object obj_child[] = child.elements().toArray();
					for (i = 0; i <= 12; i++) {
						hashKey.put(dbname+ "_"+ ((Element) obj_child[i]).attribute("name").getValue(), 
								((Element) obj_child[i]).attribute("value").getValue());
					}
					break;
				}
				i++;
			} while (true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 得到定义的系统参数
	 * 
	 * @param String
	 *            valueName 参数名称
	 * @return String 参数值
	 */
	public String getValue(String dbname, String valueName) {
		dbname = dbname.toLowerCase();
		valueName = valueName.toLowerCase();
		if (hashKey == null) {
			hashKey = new Hashtable();
		}
		if (hashKey.get(dbname + "_" + valueName) == null) {
			makeDbConn(dbname, valueName);
		}
		return (String) hashKey.get(dbname + "_" + valueName);
	}

	/**
	 * 得到当前使用数据库的系统参数
	 * 
	 * @param String
	 *            valueName 参数名称
	 * @return String 参数值
	 */
	public String getValue(String valueName) {
		return getValue("currentDb", valueName);
	}

	/**
	 * 置系统参数值
	 * 
	 * @param valueName
	 *            参数名称
	 * @param value
	 *            实际值
	 * 
	 */
	public void setValue(String valueName, String value) {

		if (hashKey.get(valueName.toLowerCase()) != null) {
			return;
		}
		synchronized (valueName.toLowerCase()) {
			hashKey.put(valueName.toLowerCase(), value);
		}
	}

	/**
	 * 句柄，供调用
	 */
	public synchronized static DBInitVO getInst() {
		if (uniqueInstance == null) {
			uniqueInstance = new DBInitVO();
		}
		return uniqueInstance;
	}
}
